package com.wn.ticket.common;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @创建人 NST
 * @创建时间 2022/8/9
 * @描述
 */
@Component
public class JwtUtils {
    @Autowired
    private JwtProperties jwtProperties;//存放有效时间和秘钥的类

    //生成jwt并储存传进来的用户参数
    public String createJWT(int id, String account) {
        DateTime now = DateTime.now();
        DateTime newTime = now.offsetNew(DateField.MINUTE, jwtProperties.getExpireMinutes());
        Map<String, Object> payload = new HashMap<String, Object>();
        //签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        //过期时间
        payload.put(JWTPayload.EXPIRES_AT, newTime);
        //生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        //载荷
        payload.put("id", id);
        payload.put("account", account);
        return JWTUtil.createToken(payload, jwtProperties.getSecret().getBytes());
    }

    //验证jwt秘钥
    public boolean verifySecretJWT(String jwt) {
        boolean verify;
        try {
            JWT token = JWTUtil.parseToken(jwt);
            JWT key = token.setKey(jwtProperties.getSecret().getBytes());
            verify = key.verify();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return verify;
    }

    //验证jwt是否超时
    public boolean verifyTimeJWT(String token) {
        String key = jwtProperties.getSecret();
        JWT jwt = null;
        try {
            jwt = JWTUtil.parseToken(token);//如果token验证失败,就返回false
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        boolean verifyTime = jwt.setKey(key.getBytes()).validate(0);//验证是否超时(注意设置密钥)
        return verifyTime;
    }

    //获取jwt中存放的用户信息
    public Object getInfo(String jwt, String name) {//name即存进载荷的名称
        JWT token = JWTUtil.parseToken(jwt);
        return token.getPayload(name);
    }
}
